package cn.admin.configcenter.registry.pojo;

import cn.admin.config.common.protocol.Swizzle;
import cn.admin.config.common.protocol.UserDataElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PurePublisherInfo extends PureClientInfo {

    public static final Logger LOG = LoggerFactory.getLogger(PurePublisherInfo.class);

    private static final long serialVersionUID = 7733357830569755416L;
    private String datumId;
    private boolean isClusterPublisher;
    private boolean isPersistent;
    private List<Serializable> data;

    @Override
    public String toString() {
        return super.toString() + " PurePublisherInfo{" +
                "datumId='" + datumId + '\'' +
                ", isClusterPublisher=" + isClusterPublisher +
                ", isPersistent=" + isPersistent +
                ", data=" + data +
                '}';
    }

    public String getDatumId() {
        return datumId;
    }

    public void setDatumId(String datumId) {
        this.datumId = datumId;
    }

    public boolean isClusterPublisher() {
        return isClusterPublisher;
    }

    public void setClusterPublisher(boolean clusterPublisher) {
        isClusterPublisher = clusterPublisher;
    }

    public boolean isPersistent() {
        return isPersistent;
    }

    public void setPersistent(boolean persistent) {
        isPersistent = persistent;
    }

    public List<Serializable> getData() {

        if (data != null && !data.isEmpty()) {
            List<Serializable> filtered = new ArrayList<>(data);
            Iterator<Serializable> it = filtered.iterator();
            while (it.hasNext()) {
                Serializable sit = it.next();
                if (sit instanceof Swizzle) {
                    try {
                        if (((Swizzle)sit).extract() == null) {
                            LOG.warn("remove service data due to empty data.");
                            it.remove();
                        }
                    } catch (Throwable t) {
                        LOG.warn("remove service data due to error: {}", t.getMessage());
                        it.remove();
                    }
                }
            }

            if (filtered.isEmpty()) {
                return filtered;
            } else {
                UserDataElement.extractShelteredData(filtered);
                return filtered;
            }
        } else {
            return this.data;
        }
    }

    public int getDataSize() {
        return null != this.data ? this.data.size() : 0;
    }

    public void setData(List<Serializable> data) {
        this.data = data;
    }
}
